<template>
  <div class="inventory-count-detail" v-loading="loading">
    <el-page-header
      content="盘点详情"
      @back="router.back"
      class="detail-header"
    />

    <el-card shadow="never" class="summary-card">
      <div class="summary-top">
        <div class="summary-left">
          <div class="code-line">
            盘点单号：
            <br />
            <span class="code">{{ detail.inventoryCountCode || '-' }}</span>
            <el-icon
              class="copy-icon"
              @click="copyCode"
              style="cursor: pointer; margin-left: 8px"
            >
              <DocumentCopy />
            </el-icon>
          </div>
        </div>
        <div class="summary-actions">
          <el-button size="small" type="primary" @click="handleInbound">
            入库
          </el-button>
          <el-button size="small" type="warning" @click="handleOutbound">
            出库
          </el-button>
          <el-button size="small" @click="handlePrint">打印</el-button>
        </div>
      </div>

      <div class="summary-info">
        <el-descriptions :column="3" border>
          <el-descriptions-item label="制单人">
            {{ displayValue(detail.documentCreator) }}
          </el-descriptions-item>
          <el-descriptions-item label="所在部门">
            {{ displayValue(detail.organizationName) }}
          </el-descriptions-item>
          <el-descriptions-item label="制单时间">
            {{ formatDateTime(detail.documentCreation) }}
          </el-descriptions-item>

          <el-descriptions-item label="盘点类型">
            {{ displayValue(detail.countTypeName) }}
          </el-descriptions-item>
          <el-descriptions-item label="盘点开始时间">
            {{ formatDate(detail.countStartTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="盘点结束时间">
            {{ formatDate(detail.countEndTime) }}
          </el-descriptions-item>

          <el-descriptions-item label="仓库名称">
            {{ displayValue(detail.warehouseName) }}
          </el-descriptions-item>
          <el-descriptions-item label="经办人">
            {{ displayValue(detail.handlerName) }}
          </el-descriptions-item>
          <el-descriptions-item label="备注" :span="1">
            {{ displayValue(detail.remarks) }}
          </el-descriptions-item>
          <el-descriptions-item label="盘点货品" :span="3">
            <el-space wrap size="small">
              <template v-if="productNameTags.length">
                <el-tag
                  v-for="name in productNameTags"
                  :key="name"
                  type="info"
                  effect="plain"
                  size="small"
                >
                  {{ name }}
                </el-tag>
              </template>
              <span v-else>-</span>
            </el-space>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <div class="summary-stats">
        <div class="stat-item">
          <div class="stat-label">盘点状态</div>
          <div class="stat-value">
            <el-tag :type="getCountResultTagType(detail.countResult)" size="small">
              {{ getCountResultText(detail.countResult) }}
            </el-tag>
          </div>
        </div>
        <div class="stat-item">
          <div class="stat-label">出库状态</div>
          <div class="stat-value">
            {{ getOutboundStatusText(detail.outboundStatus) }}
            <span v-if="detail.outboundCount !== undefined" style="color: #909399; margin-left: 4px">
              ({{ detail.outboundCompletedCount || 0 }}/{{ detail.outboundCount }})
            </span>
          </div>
        </div>
        <div class="stat-item">
          <div class="stat-label">入库状态</div>
          <div class="stat-value">
            {{ getInboundStatusText(detail.inboundStatus) }}
            <span v-if="detail.inboundCount !== undefined" style="color: #909399; margin-left: 4px">
              ({{ detail.inboundCompletedCount || 0 }}/{{ detail.inboundCount }})
            </span>
          </div>
        </div>
      </div>

      <div class="quantity-stats">
        <div class="quantity-card">
          <div class="quantity-label">盘点总数量</div>
          <div class="quantity-value">{{ detail.countQuantity || 0 }}</div>
        </div>
        <div class="quantity-card">
          <div class="quantity-label">盘盈数量 / 金额</div>
          <div class="quantity-value highlight">
            {{ detail.gainQuantity || 0 }} / {{ formatCurrency(detail.gainAmount, true) }}
          </div>
        </div>
        <div class="quantity-card">
          <div class="quantity-label">盘亏数量 / 金额</div>
          <div class="quantity-value danger">
            {{ detail.lossQuantity || 0 }} / {{ formatCurrency(detail.lossAmount, true) }}
          </div>
        </div>
      </div>
    </el-card>

    <el-card shadow="never" class="tab-card">
      <el-tabs v-model="activeTab" stretch>
        <el-tab-pane label="其他信息" name="other">
          <div class="other-info">
            <p>其他信息内容待实现</p>
          </div>
        </el-tab-pane>
        <el-tab-pane label="盘点明细" name="detail">
          <div style="margin-bottom: 12px">
            <el-button @click="handleExport">导出</el-button>
          </div>
          <div class="formula-info">
            <p>盘亏金额=盘亏数量*入库价</p>
            <p>盘盈金额=盘盈数量*入库价</p>
          </div>
          <el-table
            :data="detailList"
            border
            style="width: 100%"
            height="420px"
            show-summary
            :summary-method="summaryMethod"
            stripe
            v-loading="loading"
          >
            <el-table-column type="index" label="序号" width="60" />
            <el-table-column prop="productName" label="货品名称" min-width="140" />
            <el-table-column prop="productCode" label="货品编号" min-width="140" />
            <el-table-column prop="productTypeName" label="货品类别" min-width="140" />
            <el-table-column prop="specificationModel" label="规格型号" min-width="140" />
            <el-table-column prop="unitName" label="单位" width="100" />
            <el-table-column
              prop="bookedInventory"
              label="账面库存"
              width="120"
              align="right"
            />
            <el-table-column prop="bookedAmount" label="账面金额" width="120" align="right">
              <template #default="{ row }">
                {{ formatCurrency(row.bookedAmount, false) }}
              </template>
            </el-table-column>
            <el-table-column prop="locationName" label="盘点库位" min-width="120" />
            <el-table-column
              prop="countQuantity"
              label="盘点数量"
              width="120"
              align="right"
            />
            <el-table-column
              prop="profitLossQuantity"
              label="盈亏数量"
              width="120"
              align="right"
            >
              <template #default="{ row }">
                <span
                  :style="{
                    color:
                      row.profitLossQuantity > 0
                        ? '#67c23a'
                        : row.profitLossQuantity < 0
                        ? '#f56c6c'
                        : '',
                  }"
                >
                  {{ row.profitLossQuantity || 0 }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="countStatus" label="盘点状态" width="100">
              <template #default="{ row }">
                <el-tag :type="getCountStatusTagType(row.countStatus)" size="small">
                  {{ getCountStatusText(row.countStatus) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column
              prop="profitLossAmount"
              label="盈亏金额"
              width="120"
              align="right"
            >
              <template #default="{ row }">
                <span
                  :style="{
                    color:
                      row.profitLossAmount > 0
                        ? '#67c23a'
                        : row.profitLossAmount < 0
                        ? '#f56c6c'
                        : '',
                  }"
                >
                  {{ formatCurrency(row.profitLossAmount, false) }}
                </span>
              </template>
            </el-table-column>
            <el-table-column
              prop="referenceUnitPrice"
              label="参考单价"
              width="120"
              align="right"
            >
              <template #default="{ row }">
                {{ formatCurrency(row.referenceUnitPrice, false) }}
              </template>
            </el-table-column>
            <el-table-column prop="inboundOutboundStatus" label="出入库状态" min-width="140">
              <template #default="{ row }">
                {{ row.inboundOutboundStatus || '-' }}
              </template>
            </el-table-column>
            <el-table-column prop="remarks" label="备注" min-width="160" />
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="入库记录" name="inbound">
          <div class="other-info">
            <p>入库记录内容待实现</p>
          </div>
        </el-tab-pane>
        <el-tab-pane label="出库记录" name="outbound">
          <div class="other-info">
            <p>出库记录内容待实现</p>
          </div>
        </el-tab-pane>
        <el-tab-pane label="操作记录" name="operation">
          <div class="other-info">
            <p>操作记录内容待实现</p>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <div style="text-align: right; margin-top: 16px">
      <el-button @click="handleClose">关闭</el-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { computed, onMounted, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { DocumentCopy } from '@element-plus/icons-vue'
import moment from 'moment'
import { useRoute, useRouter } from 'vue-router'
import myaxios from '@/http/MyAxios'

interface InventoryCountDetailItem {
  checkDetailId: string
  productId: number
  productName: string
  productCode: string
  specificationModel: string
  unitName: string
  productTypeName: string
  bookedInventory: number
  bookedAmount: number
  storageLocationId: number | null
  locationName: string
  countQuantity: number
  profitLossQuantity: number
  profitLossAmount: number
  referenceUnitPrice: number
  countStatus: number
  inboundOutboundStatus: string
  remarks: string
}

interface InventoryCountDetail {
  inventoryCountId: string
  inventoryCountCode: string
  countTypeId: number
  countTypeName: string
  countStartTime?: string
  countEndTime?: string
  countQuantity: number
  gainQuantity: number
  lossQuantity: number
  gainAmount: number
  lossAmount: number
  warehouseId: number
  warehouseName: string
  handlerId: number
  handlerName: string
  remarks: string
  countResult: number
  outboundStatus: number
  inboundStatus: number
  outboundCount: number
  outboundCompletedCount: number
  inboundCount: number
  inboundCompletedCount: number
  documentCreator: string
  organizationId: number
  organizationName: string
  documentCreation?: string
  productNames: string
  detailList: InventoryCountDetailItem[]
}

const router = useRouter()
const route = useRoute()

const loading = ref(false)
const activeTab = ref('detail')

const createEmptyDetail = (): InventoryCountDetail => ({
  inventoryCountId: '',
  inventoryCountCode: '',
  countTypeId: 0,
  countTypeName: '',
  countStartTime: undefined,
  countEndTime: undefined,
  countQuantity: 0,
  gainQuantity: 0,
  lossQuantity: 0,
  gainAmount: 0,
  lossAmount: 0,
  warehouseId: 0,
  warehouseName: '',
  handlerId: 0,
  handlerName: '',
  remarks: '',
  countResult: 0,
  outboundStatus: 0,
  inboundStatus: 0,
  outboundCount: 0,
  outboundCompletedCount: 0,
  inboundCount: 0,
  inboundCompletedCount: 0,
  documentCreator: '',
  organizationId: 0,
  organizationName: '',
  documentCreation: undefined,
  productNames: '',
  detailList: [],
})

const detail = ref<InventoryCountDetail>(createEmptyDetail())
const detailList = ref<InventoryCountDetailItem[]>([])

const productNameTags = computed(() => {
  if (!detail.value?.productNames) return []
  return detail.value.productNames.split(',').filter((item) => item)
})

const mapDetailItem = (item: any): InventoryCountDetailItem => ({
  checkDetailId: String(item.checkDetailId ?? ''),
  productId: Number(item.productId ?? 0),
  productName: item.productName || '-',
  productCode: item.productCode || '-',
  specificationModel: item.specificationModel || '-',
  unitName: item.unitName || '-',
  productTypeName: item.productTypeName || '-',
  bookedInventory: Number(item.bookedInventory ?? 0),
  bookedAmount: Number(item.bookedAmount ?? 0),
  storageLocationId:
    item.storageLocationId === null || item.storageLocationId === undefined
      ? null
      : Number(item.storageLocationId),
  locationName: item.locationName || '',
  countQuantity: Number(item.countQuantity ?? 0),
  profitLossQuantity: Number(item.profitLossQuantity ?? 0),
  profitLossAmount: Number(item.profitLossAmount ?? 0),
  referenceUnitPrice: Number(item.referenceUnitPrice ?? 0),
  countStatus: Number(item.countStatus ?? 0),
  inboundOutboundStatus: item.inboundOutboundStatus || '',
  remarks: item.remarks || '',
})

const loadDetail = async () => {
  const inventoryCountId = route.query.inventoryCountId
  if (!inventoryCountId) {
    ElMessage.error('缺少盘点单ID')
    return
  }

  loading.value = true
  try {
    const res = await myaxios.get('/api/InventoryCount/GetInventoryCountDetail', {
      params: { inventoryCountId },
    })
    if (res.data?.success || res.data?.code === 200) {
      const data = res.data.data || {}
      const mappedDetail: InventoryCountDetail = {
        ...createEmptyDetail(),
        ...data,
        detailList: (data.detailList || []).map((item: any) => mapDetailItem(item)),
      }
      detail.value = mappedDetail
      detailList.value = mappedDetail.detailList
    } else {
      ElMessage.error(res.data?.message || '获取盘点详情失败')
    }
  } catch (error) {
    console.error('获取盘点详情失败:', error)
    ElMessage.error('获取盘点详情失败')
  } finally {
    loading.value = false
  }
}

const displayValue = (value: unknown) => {
  if (value === null || value === undefined) return '-'
  if (typeof value === 'string' && value.trim() === '') return '-'
  return value
}

const formatDate = (date?: string) => {
  if (!date) return '-'
  return moment(date).format('YYYY-MM-DD')
}

const formatDateTime = (date?: string) => {
  if (!date) return '-'
  return moment(date).format('YYYY-MM-DD HH:mm:ss')
}

const formatCurrency = (value: number | string, showSymbol = true) => {
  const num = Number(value || 0)
  return showSymbol ? `¥${num.toFixed(2)}` : num.toFixed(2)
}

const getCountResultTagType = (result: number) => {
  switch (result) {
    case 0:
      return 'info'
    case 1:
      return 'warning'
    case 2:
      return 'success'
    default:
      return 'info'
  }
}

const getCountResultText = (result: number) => {
  switch (result) {
    case 0:
      return '草稿'
    case 1:
      return '有盈亏'
    case 2:
      return '无盈亏'
    default:
      return '未知'
  }
}

const getOutboundStatusText = (status: number) => {
  switch (status) {
    case 0:
      return '未出库'
    case 1:
      return '部分出库'
    case 2:
      return '已出库'
    default:
      return '未知'
  }
}

const getInboundStatusText = (status: number) => {
  switch (status) {
    case 0:
      return '未入库'
    case 1:
      return '部分入库'
    case 2:
      return '已入库'
    default:
      return '未知'
  }
}

const getCountStatusTagType = (status: number) => {
  switch (status) {
    case 0:
      return 'info'
    case 1:
      return 'success'
    case 2:
      return 'danger'
    default:
      return 'info'
  }
}

const getCountStatusText = (status: number) => {
  switch (status) {
    case 0:
      return '无盈亏'
    case 1:
      return '盘盈'
    case 2:
      return '盘亏'
    default:
      return '未知'
  }
}

const summaryMethod = ({ columns, data }: any) => {
  const sums: string[] = []
  columns.forEach((column: any, index: number) => {
    if (index === 0) {
      sums[index] = '合计'
      return
    }
    const values = data.map((item: any) => Number(item[column.property]))
    if (!values.every((value: number) => isNaN(value))) {
      const property = column.property
      if (property === 'bookedInventory') {
        sums[index] = values.reduce((prev: number, curr: number) => {
          const value = Number(curr)
          if (!isNaN(value)) {
            return prev + curr
          } else {
            return prev
          }
        }, 0)
      } else if (property === 'bookedAmount') {
        sums[index] = `¥${values
          .reduce((prev: number, curr: number) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          .toFixed(2)}`
      } else if (property === 'countQuantity') {
        sums[index] = values.reduce((prev: number, curr: number) => {
          const value = Number(curr)
          if (!isNaN(value)) {
            return prev + curr
          } else {
            return prev
          }
        }, 0)
      } else if (property === 'profitLossQuantity') {
        const gainSum = data
          .filter((item: any) => item.profitLossQuantity > 0)
          .reduce((sum: number, item: any) => sum + Number(item.profitLossQuantity || 0), 0)
        const lossSum = data
          .filter((item: any) => item.profitLossQuantity < 0)
          .reduce((sum: number, item: any) => sum + Math.abs(Number(item.profitLossQuantity || 0)), 0)
        sums[index] = `盘盈: ${gainSum} 盘亏: ${lossSum}`
      } else if (property === 'profitLossAmount') {
        const gainSum = data
          .filter((item: any) => item.profitLossAmount > 0)
          .reduce((sum: number, item: any) => sum + Number(item.profitLossAmount || 0), 0)
        const lossSum = data
          .filter((item: any) => item.profitLossAmount < 0)
          .reduce((sum: number, item: any) => sum + Math.abs(Number(item.profitLossAmount || 0)), 0)
        sums[index] = `盘盈: ¥${gainSum.toFixed(2)} 盘亏: ¥${lossSum.toFixed(2)}`
      } else {
        sums[index] = ''
      }
    } else {
      sums[index] = ''
    }
  })
  return sums
}

const copyCode = () => {
  const code = detail.value?.inventoryCountCode
  if (code) {
    navigator.clipboard.writeText(code).then(() => {
      ElMessage.success('盘点单号已复制到剪贴板')
    })
  }
}

const handleInbound = () => {
  ElMessage.info('入库功能待实现')
}

const handleOutbound = () => {
  ElMessage.info('出库功能待实现')
}

const handlePrint = () => {
  ElMessage.info('打印功能待实现')
}

const handleExport = () => {
  ElMessage.info('导出功能待实现')
}

const handleClose = () => {
  router.back()
}

onMounted(() => {
  loadDetail()
})
</script>

<style scoped>
.inventory-count-detail {
  padding: 16px;
}

.detail-header {
  margin-bottom: 16px;
}

.summary-card {
  margin-bottom: 16px;
}

.summary-top {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
}

.summary-left {
  flex: 1;
}

.code-line {
  font-size: 14px;
  color: #606266;
  line-height: 1.8;
}

.code {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin-right: 8px;
}

.copy-icon {
  color: #909399;
  font-size: 16px;
}

.copy-icon:hover {
  color: #409eff;
}

.summary-actions {
  display: flex;
  gap: 8px;
}

.summary-info {
  margin-bottom: 20px;
}

.summary-stats {
  display: flex;
  gap: 40px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.stat-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.stat-value {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.quantity-stats {
  display: flex;
  gap: 16px;
  margin-top: 24px;
}

.quantity-card {
  flex: 1;
  padding: 12px 16px;
  border: 1px solid #ebeef5;
  border-radius: 6px;
  background-color: #fafafa;
}

.quantity-label {
  font-size: 13px;
  color: #909399;
  margin-bottom: 6px;
}

.quantity-value {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.quantity-value.highlight {
  color: #67c23a;
}

.quantity-value.danger {
  color: #f56c6c;
}

.tab-card {
  margin-bottom: 16px;
}

.formula-info {
  margin-bottom: 12px;
  padding: 8px 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
  font-size: 12px;
  color: #606266;
}

.formula-info p {
  margin: 4px 0;
}

.other-info {
  padding: 40px;
  text-align: center;
  color: #909399;
}
</style>

